package com.sdnu.service.service.oss.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.sdnu.service.service.oss.OssService;
import com.sdnu.service.utiils.oss.ConstantPropertiesUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @Author: Zhao YunLai
 * @Date: 2021/12/06/17:04
 * @Description:
 */
@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uploadFileByLocalPath(String filePath, String host) {
        //1.获取基本信息
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;
        String endPoint = ConstantPropertiesUtil.END_POINT;
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;

        OSS ossClient = null;
        try {
            //2.初始化对象
            ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);

            //3.根据文件路径获取文件
            File file = new File(filePath);

            //4.获取文件名称
            String filename = file.getName();

            //在文件名称里面添加随机唯一的值,使文件名唯一，防止后面名称相同的文件覆盖前面的文件
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");

            //yuyuyu01.jpg
            filename = uuid + filename;

            //把文件按照日期进行分类
            //获取当前日期
            //2019//11/12/o1.jpg
//            String datePath = new DateTime().toString("yyyy/MM/dd");

            //拼接
            if(!StringUtils.isEmpty(host)){
                filename = host + "/" + filename;
            }

            //4.调用oss方法实现上传
            //第一个参数：Bucket名称
            //第二个参数：上传到oss文件路径和路径名称 aa//bb//01.jpg
            //第三个参数：上传文件的输入流
            ossClient.putObject(bucketName, filename, file);

            //把上传之后的文件路径返回
            //需要把上传到阿里云oss的路径手动拼接出来
            String url = "https://" + bucketName + "." + endPoint + "/" + filename;
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            //关闭OSSClient
            if(ossClient!=null){
                ossClient.shutdown();
            }
        }
    }
}
